#include<unordered_map>
#include<fstream>
#include"UdpServer.hpp"

const static std::string defaultdict = "./dictionary.txt";
const static std::string sep = "：";

class Dict
{
public:
    Dict(const std::string &path = defaultdict):_dict_path(path)
    {}
    bool LoadWord()
    {
        std::ifstream in(_dict_path);
        if(!in.is_open())
        {
            LOG(LogLevel::FATAL) << "open file error...";
            return false;
        }
        std::string line;
        while(std::getline(in,line))//注意是从文件流里去读取，一次读一行
        {
            auto pos = line.find(sep);
            if(pos == std::string::npos)
            {  
                LOG(LogLevel::FATAL) << "解析文件失败";
                continue;
            }
            std::string english = line.substr(0,pos);
            std::string chinese = line.substr(pos + sep.size());
            if(english.empty()||chinese.empty())
            {
                LOG(LogLevel::FATAL) << "没有有效内容";
                continue;//返回继续进行解析文件
            }
            _dict[english] = chinese;
            LOG(LogLevel::DEBUG) << "加载" << line << "成功";
        }
        in.close();
        return true;
    }
    std::string Transact(std::string word,InetAddr &client)
    {
        auto pos = _dict.find(word);
        if(pos == _dict.end())
        {
            LOG(LogLevel::DEBUG) << "进入到了翻译模块, [" << client.GetIp() << " : " << client.GetPort() << "]# " << word << "->None";
            return "None";
        }
        LOG(LogLevel::DEBUG) << "进入到了翻译模块, [" << client.GetIp() << " : " << client.GetPort() << "]# " << word << "->" << pos->second;
        return pos->second;
    }
    ~Dict()
    {}
private:
    std::string _dict_path;
    std::unordered_map<std::string,std::string> _dict;
};